
<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-lx-cascades"></i>
                    {{pageTitle}}
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>

        <el-container :style="{'min-height': containerHeight + 'px'}">
            <el-container style="border-top: 1px solid rgb(88, 149, 194)">
                <el-aside>
                    <el-header>
                        <h4 style>角色</h4>
                    </el-header>
                    <el-table
                        ref="singleTableRole"
                        :data="roleData"
                        highlight-current-row
                        border
                        :height="containerHeight+'px'"
                        style="width: 100%"
                        @select="handleSelect"
                        @select-all="onSelectAll"
                    >
                        <el-table-column type="selection" width="60" align="center"></el-table-column>
                        <el-table-column type="index" label="序号" width="50"></el-table-column>
                        <el-table-column property="roleName" label="角色名称"></el-table-column>
                    </el-table>
                </el-aside>
                <div class="tree_show"></div>
                <el-aside>
                    <el-header>
                        <h4 style>模块</h4>
                    </el-header>
                    <el-table
                        ref="singleTable"
                        :data="tableData"
                        highlight-current-row
                        border
                        @select="handleSelect1"
                        @select-all="onSelectAll1"
                        :height="containerHeight+'px'"
                        style="width: 100%"
                    >
                        <el-table-column type="selection" width="60" align="center"></el-table-column>
                        <el-table-column type="index" label="序号" width="50"></el-table-column>
                        <el-table-column property="name" label="权限名称"></el-table-column>
                    </el-table>
                </el-aside>

                <div class="tree_show"></div>
                <el-main>
                    <el-header>
                        <h4>功能权限</h4>
                    </el-header>

                    <div class="handle-box">
                        <el-button type="primary" icon="el-icon-folder-checked" @click="save">保存</el-button>
                        <el-button type="warning" icon="el-icon-finished" @click="chooseAll">全选</el-button>
                        <el-button type="danger" icon="el-icon-delete" @click="chooseClean">清空</el-button>
                    </div>
                    <el-tree
                        ref="treeData"
                        :data="treeData"
                        :props="defaultProps"
                        node-key="id"
                        @check-change="handleSelectionChange"
                        :default-checked-keys="resourceCheckedKey"
                        show-checkbox
                        default-expand-all
                    ></el-tree>
                </el-main>
            </el-container>
        </el-container>
    </div>
</template>

<script>
import appMain from '../../../utils/app_main';
export default {
    data() {
        return {
            containerHeight: '',
            pageTitle: '',
            tableData: [],
            treeData: [],
            roleData: [],
            defaultProps: {
                children: 'children',
                label: 'name',
                value: 'id'
            },
            currentRow: {},
            currentRoleRow: {},
            resourceCheckedKey: [],
            multipleSelection: []
        };
    },
    created() {
        this.getData();
        this.getRoleData();
        this.findAllChildren(this.treeData, this.resourceCheckedKey);
    },
    mounted() {
        var div_height = window.screen.availHeight;
        var height = div_height - 100;
        this.containerHeight = height - 160;
        this.pageTitle = this.$router.currentRoute.meta.title;
    },
    watch: {
        currentRoleRow: function(newVal) {
            if (newVal == {}) {
                this.treeData = [];
            }
        },
        currentRow: function(newVal) {
            console.log('currentRow', newVal);
            if (!newVal.id) {
                this.treeData = [];
            }
        }
    },
    methods: {
        getData() {
            appMain
                .permissionFind({})
                .then(res => {
                    if (res.data.code === 20000) {
                        this.tableData = res.data.data;
                    } else {
                        this.$message.error('服务器繁忙，请稍后再试');
                    }
                })
                .catch(err => {
                    console.log(err);
                });
        },
        getRoleData() {
            appMain
                .roleFindAllPageByDTO(this.query)
                .then(res => {
                    if (res.data.code === 20000) {
                        this.roleData = res.data.data;
                    } else {
                        this.loading = false;
                        this.$message.error(res.data.message);
                    }
                })
                .catch(err => {
                    this.loading = false;
                    console.log(err);
                });
        },
        // 获取树的数据
        getTree() {
            appMain
                .permissionFindModules({ moduleId: this.currentRow.id, roleId: this.currentRoleRow.id })
                .then(res => {
                    if (res.data.code === 20000) {
                        this.treeData = res.data.data;
                        if (this.treeData != null && this.treeData.length > 0) {
                            this.findAllChildren(this.treeData, this.resourceCheckedKey);
                        }
                    } else {
                        this.$message.error(res.data.message);
                    }
                })
                .catch(err => {
                    console.log(err);
                });
        },
        handleCurrentChange(val) {
            this.currentRow = val;
            this.getTree();
            console.log('handleCurrentChange', val);
        },
        // el-tree 复选框默认选中事件
        handleSelectionChange(val) {
            // this.multipleSelection  这个数组用来存储所有半选的节点和全选的节点  用于保存的时候将数据传给后台
            // 将半选和全选的节点全都存储在一个数组里面   concat 方法是合并(全选和半选)两个数组
            this.multipleSelection = this.$refs.treeData.getHalfCheckedNodes().concat(this.$refs.treeData.getCheckedNodes());
            console.log('handleSelectionChange', this.multipleSelection);
        },
        findAllNode(data, arr) {
            data.forEach((item, index) => {
                if (item.children) {
                    arr.push(item.id);
                    this.findAllChildren(item.children, arr);
                } else {
                    arr.push(item.id);
                }
            });
        },
        // 遍历找出所有子节点
        findAllChildren(data, arr) {
            data.forEach((item, index) => {
                if (item.children) {
                    this.findAllChildren(item.children, arr);
                } else if (item.roleChoose == 1) {
                    // validSign 这个字段是后台用来判断前台是否默认选中的字段  validSign == 1 是选中  等于 0 是非选中 (根据你们后台实际参数进行修改)
                    // 然后我们将 validSign == '1' 的所有子节点全部存储在arr 里面
                    arr.push(item.id);
                }
            });
        },
        save() {
            let multipleSelection = this.$refs.treeData.getHalfCheckedKeys().concat(this.$refs.treeData.getCheckedKeys());
            let params = {
                moduleId: this.currentRow.id,
                roleId: this.currentRoleRow.id,
                permissionIds: multipleSelection
            };
            appMain
                .updatePermissionsByModuleId(params)
                .then(res => {
                    if (res.data.code === 20000) {
                        this.$message.success(res.data.message);
                        this.getTree();
                    } else {
                        this.$message.error(res.data.message);
                    }
                })
                .catch(err => {
                    console.log(err);
                });
        },
        chooseAll() {
            // 二次确认删除
            this.$confirm('确定选择全部功能权限？', '提示', {
                type: 'warning'
            })
                .then(() => {
                    this.findAllNode(this.treeData, this.resourceCheckedKey);
                    this.$refs.treeData.setCheckedKeys(this.resourceCheckedKey);
                })
                .catch(() => {});
        },
        chooseClean() {
            // 二次确认删除
            this.$confirm('确定清空全部功能权限？', '提示', {
                type: 'warning'
            })
                .then(() => {
                    this.resourceCheckedKey = [];
                    this.$refs.treeData.setCheckedKeys([]);
                })
                .catch(() => {});
        },
        // 勾选的时候来判断 让其变成单选
        handleSelect(val, row) {
            if (val.length > 1) {
                this.$refs.singleTableRole.clearSelection(); // 清空所有选择
                val.shift();
                this.$refs.singleTableRole.toggleRowSelection(row); //  选中当前选择
            }

            let selected = val.length && val.indexOf(row) !== -1;
            //console.log('handleSelect', selected); // true就是选中，0或者false是取消选中
            //console.log('handleSelect', row);
            if (selected) {
                this.currentRoleRow = row;
                console.log('handleSelect', this.currentRow);
                if (this.currentRow.id) {
                    this.getTree();
                }
            } else {
                this.currentRoleRow = {};
            }
        },
        onSelectAll() {
            this.$refs.singleTableRole.clearSelection(); //这个是清除所有选择项，当选择全部时，清除所有选择项
            this.currentRoleRow = {};
        },
        // 勾选的时候来判断 让其变成单选
        handleSelect1(val, row) {
            if (val.length > 1) {
                this.$refs.singleTable.clearSelection(); // 清空所有选择
                val.shift();
                this.$refs.singleTable.toggleRowSelection(row); //  选中当前选择
            }

            let selected = val.length && val.indexOf(row) !== -1;
            //console.log('handleSelect', selected); // true就是选中，0或者false是取消选中
            //console.log('handleSelect', row);
            if (selected) {
                this.currentRow = row;

                if (this.currentRoleRow.id) {
                    this.getTree();
                } else {
                    this.$message.info('请选择角色!');
                }
            } else {
                this.currentRow = {};
            }
        },
        onSelectAll1() {
            this.$refs.singleTable.clearSelection(); //这个是清除所有选择项，当选择全部时，清除所有选择项
            this.currentRow = {};
        }
    }
};
</script>



<style lang="css" scoped>
.el-header {
    color: #fff;
    background-color: rgb(58, 149, 222);
    height: 35px !important;
    border-radius: 2px;
    text-align: left;
    font-size: 16px;
}

h4 {
    padding-top: 5px;
}

.el-aside {
    background-color: rgb(238, 241, 246);
}

.el-main {
    padding: 0px !important;
    background-color: rgb(238, 241, 246);
}

.tree_show {
    width: 3px;
    background-color: rgb(121, 183, 231);
}
.handle-box {
    margin-top: 5px;
    margin-bottom: 5px;
    margin-left: 5px;
    flex-wrap: wrap;
    font-size: 12px;
}
</style>
